package javax.per.toolkit.tools.msg;

import java.io.File;
import java.io.FileOutputStream;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;

import javax.per.toolkit.file.DetectEncoding;
import javax.per.toolkit.tools.Fun;
import javax.per.toolkit.tools.Log;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

public class SetMsg {

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		String key = null;
		String value = null;
		String des = null;
		System.out.print("key:\t");
		key = Fun.getConsoleString();
		System.out.print("value:\t");
		value = Fun.getConsoleString();
		System.out.print("remark:\t");
		des = Fun.getConsoleString();
		Fun.pl(key);
		Fun.pl(value);
		if (key == null || key.trim().length() == 0 || value == null
				|| value.length() == 0) {
			Log.getLogger().error(Msg.get("NULLPARM"));
			return;
		} else {
			key = key.trim();
			String res = Msg.get(key);
			if (res != null) {
				Log.getLogger().error(Msg.get("OBJEXISTS"));
			} else {
				SAXReader reader = new SAXReader();
				Document doc = null;
				try {
					doc = reader.read(Msg.class.getResource("msg.xml"));
				} catch (DocumentException e) {
					e.printStackTrace();
				}
				Element root = (Element) doc.selectSingleNode("msgs");
				Element ele = root.addElement("msg");
				ele.addAttribute("key", key);
				ele.addAttribute("value", value);
				if (des != null && des.length() != 0)
					ele.addAttribute("remark", des);
				OutputFormat format = OutputFormat.createPrettyPrint();
				format.setIndent(true);
				format.setIndent("\t");
				format.setEncoding("utf-8");
				format.setNewlines(true);
				String filepath = Msg.class.getResource("msg.xml").getFile();

				try {
					filepath = URLDecoder.decode(filepath,
							DetectEncoding.getEncoding(filepath));
				} catch (UnsupportedEncodingException e1) {
					e1.printStackTrace();
				}
				File out = new File(filepath);
				try {
					XMLWriter xml = new XMLWriter(new FileOutputStream(out),
							format);
					xml.write(doc);
				} catch (Exception e) {
					e.printStackTrace();
				}
			}
		}
	}

}
